import koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import { Sequelize,DataTypes,Op} from 'sequelize'
import cors from '@koa/cors'

let app = new koa();

let router =new Router()

let sequelize =new Sequelize('aaa','root','123456',{
    dialect:'mysql',
    host:'localhost'
})

let Book =sequelize.define('book',{
    bookName: DataTypes.STRING,
    author:DataTypes.STRING,

})



app.use(cors())
app.use(bodyParser())

router.get('/book',async (ctx)=>{

    
    let book =await Book.findAll();
    console.log(book);
    ctx.body = {
       
        code : 1000,
        data: book,
        msg:"成功"
    }
})

router.post('/book',async (ctx)=>{
    let obj =ctx.request.body;

    let res =await Book.create(obj)
    ctx.body={
        code: 1000,
        data:res,
        msg:"新增成功"
    }
})

router.put('/book/:id', async (ctx) => {
    let id = ctx.params.id;
    let obj = ctx.request.body;
    let res = await Book.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        data: res,
        msg: '修改成功'
    }
})
router.delete('/book/:id', async (ctx) => {
    let id = ctx.params.id || 0;
    let res=await Book.destroy({
        where:{
            id
        }
    })
    ctx.body = {
        code:1000,
        data:res,
        msg:'删除成功'
    }
})
router.get('/book/:id', async (ctx) => {
    let id = ctx.params.id || 0;
    let res =await Book.findByPk(id);
    ctx.body = {
        code:1000,
        data:res,
        msg:'获取指定数据成功'
    }
})

app.use(router.routes())


let appPort = 3000;
app.listen (appPort)
console.log(`http://localhost:${appPort}`);
